package com.shadowlight.hero_story.cmdHandler;

import com.shadowlight.hero_story.Broadcaster;
import com.shadowlight.hero_story.msg.GameMsgProtocol;
import com.shadowlight.hero_story.pojo.User;
import com.shadowlight.hero_story.pojo.UserRepository;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description 用户进入处理器
 * @Author cz
 * @Date 2022/3/2
 */
@Slf4j
public class UserEntryCmdHandler implements ICmdHandler<GameMsgProtocol.UserEntryCmd> {

    @Override
    public void handle(ChannelHandlerContext channelHandlerContext, GameMsgProtocol.UserEntryCmd msg) {
        //获取英雄进入战斗场景
        Integer id = (Integer) channelHandlerContext.channel().attr(AttributeKey.valueOf("userId")).get();
        if (id == null) return;
        User user = UserRepository.getInstance().getUserById(id);
        log.debug("有用户进入战斗场景: {}", user == null ? "非法进入用户" : user.toString());
        if (user == null) return;

        GameMsgProtocol.UserEntryResult.Builder userEntryResultBuilder = GameMsgProtocol.UserEntryResult.newBuilder();
        userEntryResultBuilder.setUserId(user.getId());
        userEntryResultBuilder.setUserName(user.getUserName());
        userEntryResultBuilder.setHeroAvatar(user.getHeroAvatar());

        GameMsgProtocol.UserEntryResult userEntryResult = userEntryResultBuilder.build();
        Broadcaster.broadcast(userEntryResult);
    }
}
